package com.allm.ai.common.repository;

import com.allm.ai.common.entity.ModelTag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 模型标签数据访问层
 */
@Repository
public interface ModelTagRepository extends JpaRepository<ModelTag, Long> {

    /**
     * 根据名称查找标签
     */
    Optional<ModelTag> findByName(String name);

    /**
     * 查找所有启用的标签，按排序字段排序
     */
    List<ModelTag> findByIsActiveTrueOrderBySortOrder();

    /**
     * 根据模型ID查找启用的标签
     */
    @Query("SELECT t FROM ModelTag t " +
           "JOIN AiModelTag mt ON t.id = mt.tagId " +
           "WHERE mt.modelId = :modelId AND t.isActive = true AND mt.isActive = true " +
           "ORDER BY t.sortOrder")
    List<ModelTag> findByModelId(@Param("modelId") Long modelId);

    /**
     * 根据模型ID查找所有标签（包括禁用的关联）
     */
    @Query("SELECT t FROM ModelTag t " +
           "JOIN AiModelTag mt ON t.id = mt.tagId " +
           "WHERE mt.modelId = :modelId AND t.isActive = true " +
           "ORDER BY t.sortOrder")
    List<ModelTag> findByModelIdIncludeInactive(@Param("modelId") Long modelId);

    /**
     * 检查标签名称是否存在（排除指定ID）
     */
    boolean existsByNameAndIdNot(String name, Long id);

    boolean existsByName(String name);
}
